package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取账户密码，告诉编码方式
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //查漏
        if (username == null || username.equals("") || password == null || password.equals("")) {
            String html = "<h3>登录失败！</h3>";
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        //匹配
        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if (username == null){
            String html = "<h3>用户名或密码错误! </h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        if (!password.equals(user.getPassword())){
            String html = "<h3>用户名或密码错误! </h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        //创建会话，服务器保存一定的数据
        HttpSession session = req.getSession(true);
        //存储
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setStatus(403);
            return;
        }

        User user = (User)session.getAttribute("user");
        if (user == null){
            resp.setStatus(403);
            return;
        }

        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        //密码置空
        user.setPassword("");
        //返回登录对象
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
